package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SongType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysSong;
import com.ruoyi.system.service.ISysSongService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 歌单Controller
 *
 * @author ruoyi
 * @date 2023-05-20
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/song")
@Slf4j
@Tag(name = "歌单")
public class SysSongController extends BaseController {

    private final ISysSongService sysSongService;

    /**
     * 查询歌单列表
     */
    @Operation(summary = "查询歌单列表")
    @PreAuthorize("@ss.hasPermi('system:song:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysSong sysSong) {
        startPage();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysSong> list;
        if (!user.isAdmin()) {
            sysSong.setSinger(user.getUserName());
        }
        list = sysSongService.selectSysSongList(sysSong);
        return getDataTable(list);
    }

    /**
     * 导出歌单列表
     */
    @Operation(summary = "导出歌单列表")
    @PreAuthorize("@ss.hasPermi('system:song:export')")
    @Log(title = "歌单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysSong sysSong) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!"admin".equals(user.getUserName())) {
            sysSong.setSinger(user.getUserName());
        }
        List<SysSong> list = sysSongService.selectSysSongList(sysSong);
        List<SysSong> songList = new ArrayList<>();
        for (SysSong song : list) {
            SysSong newSong = new SysSong();
            BeanUtils.copyProperties(song, newSong);
            newSong.setTypeStr(song.getType() == 1 ? SongType.MUSiC.getInfo() : SongType.DANCE.getInfo());
            songList.add(newSong);
        }
        ExcelUtil<SysSong> util = new ExcelUtil<>(SysSong.class);
        util.exportExcel(response, songList, "歌单数据");
    }

    /**
     * 获取歌单详细信息
     */
    @Operation(summary = "获取歌单详细信息")
    @PreAuthorize("@ss.hasPermi('system:song:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysSongService.selectSysSongById(id));
    }

    /**
     * 新增歌单
     */
    @Operation(summary = "新增歌单")
    @PreAuthorize("@ss.hasPermi('system:song:add')")
    @Log(title = "歌单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysSong sysSong) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        sysSong.setSinger(user.getUserName());
        String songName = capitalize(sysSong.getName());
        sysSong.setName(songName);
        return toAjax(sysSongService.insertSysSong(sysSong));
    }

    /**
     * 修改歌单
     */
    @Operation(summary = "修改歌单")
    @PreAuthorize("@ss.hasPermi('system:song:edit')")
    @Log(title = "歌单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysSong sysSong) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        sysSong.setSinger(user.getUserName());
        return toAjax(sysSongService.updateSysSong(sysSong));
    }

    /**
     * 删除歌单
     */
    @Operation(summary = "删除歌单")
    @PreAuthorize("@ss.hasPermi('system:song:remove')")
    @Log(title = "歌单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysSongService.deleteSysSongByIds(ids));
    }

    /**
     * 下载模板
     */
    @Operation(summary = "下载模板")
    @PreAuthorize("@ss.hasPermi('system:song:export')")
    @Log(title = "歌单", businessType = BusinessType.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        ExcelUtil<SysSong> util = new ExcelUtil<>(SysSong.class);
        util.exportExcel(response, null, "歌单数据");
    }

    @Operation(summary = "歌单导入")
    @Log(title = "歌单导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public void importExcel(MultipartFile file) {
        ExcelUtil<SysSong> util = new ExcelUtil<>(SysSong.class);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        try {
            List<SysSong> songList = util.importExcel(file.getInputStream());
            for (SysSong sysSong : songList) {
                if (SongType.MUSiC.getInfo().equals(sysSong.getTypeStr())) {
                    sysSong.setType(SongType.MUSiC.getCode());
                } else {
                    sysSong.setType(SongType.DANCE.getCode());
                }
                sysSong.setSinger(user.getUserName());
                if (sysSong.getDate() == null) {
                    sysSong.setDate(new Date());
                }
                String songName = capitalize(sysSong.getName());
                sysSong.setName(songName);
                sysSongService.insertSysSong(sysSong);
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    public String capitalize(String str) {
        String name = str.trim();
        //将英文句子利用空格分隔成字符串数组
        String[] str1 = name.split(" ");
        //用于存放将单词首字母大写后的字符串
        StringBuilder str2 = new StringBuilder();
        for (int i = 0; i < str1.length; i++) {
            //substring(0,1).toUpperCase()是将单词第一个字母大写，再连接上后面的字母substring(1),注意区分substring的两种用法
            str1[i] = str1[i].substring(0, 1).toUpperCase() + str1[i].substring(1);
            //该判断是用来隔开进行以上操作后的单词，若不是最后一个单词，中间需要用空格隔开
            if (i == str1.length - 1) {
                str2.append(str1[i]);
            } else {
                str2.append(str1[i]).append(" ");
            }
        }
        return str2.toString();
    }
}
